package kgame5.kengine {
import kgame5.kengine.gameunit.GameUnit;

import flash.utils.Dictionary;

/**
 * @author kk
 * 游戏世界，存储各个GameUnit,并处理碰撞之类
 */
public class GameWorld {
	
	private var dict_all:Dictionary;
	private var arr_collideable:Vector.<GameUnit>;//可碰撞的
	
	public function GameWorld(){
		
	}
	
	public function init():void{
		dict_all=new Dictionary();
		arr_collideable=new Vector.<GameUnit>();
		
		EngineContext.getInstance().init();
	}
	
	public function clear():void{
		dict_all=null;
		arr_collideable=null;
		
		EngineContext.getInstance().clear();
	}
	
	public function update():void{
		//检测碰撞，将结果填充到一个表中
		runCollideTest();
		
		//逐个执行逻辑
		for each(var gu:GameUnit in dict_all){
			
			gu.update();//更新
			
			gu.clearCollideInfo();//actor清空自己的hitQueue
		}
	}
	
	//填充各个元素的碰撞列表
	private function runCollideTest():void{
		//T.p("---------------检测全体碰撞-----------");
		
		var len:int=arr_collideable.length;
		
		for(var i:int=0;i<len-1;i++){
			var src:GameUnit=arr_collideable[i] as GameUnit;
			for(var j:int=i+1;j<len;j++){
				var aim:GameUnit=arr_collideable[j] as GameUnit;
				
				if(src.hard.HitTestAABB(aim.hard)){
					src.addCollideItem(aim);
					aim.addCollideItem(src);
				}
			}
		}
	}
	
	//===================增加删除之类的==================
	public function addChild(gu:GameUnit):void{
		
		//总类表中添加
		dict_all[gu.getID()]=gu;
		
		if(gu.isCollideAble){
			arr_collideable.push(gu);
		}
		
		//EngineContext添加
		EngineContext.getInstance().addGU(gu);
	}
	
	public function findChild(guID:int):GameUnit{
		return dict_all[guID];
	}
	
	//返回是否删除成功
	public function removeChild(guID:int):void{
		
		var gu:GameUnit=findChild(guID);
		if(gu==null){
			return ;
		}
		
		//总列表中删除
		delete dict_all[guID];
		
		//从碰撞列表中删除
		var idx:int=arr_collideable.indexOf(gu);
		if(idx!=-1){
			arr_collideable.splice(idx, 1);
		}
		
		//EngineContext删除
		EngineContext.getInstance().removeGU(gu.getID());
	}
}//end of class
}
